package com.bilibili.service.impl;

import com.alipay.api.domain.Product;
import com.bilibili.dto.CartoonDto;
import com.bilibili.entity.PicCartoon;
import com.bilibili.entity.PicCategory;
import com.bilibili.entity.PicRegion;
import com.bilibili.exception.BusinessException;
import com.bilibili.mapper.PicCartoonMapper;
import com.bilibili.mapper.PicCategoryMapper;
import com.bilibili.mapper.PicPageMapper;
import com.bilibili.mapper.PicRegionMapper;
import com.bilibili.service.PicCartoonService;
import com.bilibili.utils.RedisOperations;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.bilibili.constant.BusinessConstant.*;

@Service
public class PicCartoonServiceImpl implements PicCartoonService {

    @Autowired
    private PicCartoonMapper picCartoonMapper;

    @Autowired
    private PicPageMapper picPageMapper;

    @Autowired
    private PicCategoryMapper picCategoryMapper;

    @Autowired
    private PicRegionMapper picRegionMapper;

    @Autowired
    private RedisOperations redisOperations;

    @Override
    public List<PicCartoon> getAllCartoon() {
        return getLatestPage(picCartoonMapper.getAllCartoon());
    }

    @Override
    public List<PicCartoon> getCartoonByCategoryId(Integer categoryId) {
        if (CARTOON_MAX_CATEGORY.equals(categoryId)){
            return getLatestPage(picCartoonMapper.getAllCartoon());
        }
        return getLatestPage(picCartoonMapper.getCartoonByCategoryId(categoryId));
    }

    @Override
    public List<PicCartoon> getCartoonByRegionId(Integer regionId) {
        return getLatestPage(picCartoonMapper.getCartoonByRegionId(regionId));
    }

    @Override
    public PicCartoon getCartoonById(Integer cartoonId) {
        PicCartoon cartoon = picCartoonMapper.getCartoonById(cartoonId);
        if (Objects.isNull(cartoon)){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画id不存在");
        }
        Integer count = picPageMapper.getPageCountByCartoonId(cartoon.getId());
        cartoon.setLatestPage(count);
        return cartoon;
    }


    @Override
    public List<PicCartoon> getCartoonByIds(Integer categoryId, Integer regionId) {
        if (categoryId.equals(CARTOON_MAX_CATEGORY) && regionId.equals(CARTOON_MAX_REGION)) {
            return getLatestPage(picCartoonMapper.getAllCartoon());
        }
        if (categoryId.equals(CARTOON_MAX_CATEGORY)) {
            return getLatestPage(picCartoonMapper.getCartoonByRegionId(regionId));
        }
        if (regionId.equals(CARTOON_MAX_REGION)) {
            return getLatestPage(picCartoonMapper.getCartoonByCategoryId(categoryId));
        }
        List<PicCartoon> cartoonByRegionId = picCartoonMapper.getCartoonByRegionId(regionId);
        List<PicCartoon> cartoonByCategoryId = picCartoonMapper.getCartoonByCategoryId(categoryId);
        cartoonByCategoryId.retainAll(cartoonByRegionId);
        return getLatestPage(cartoonByCategoryId);
    }

    @Override
    public List<PicCartoon> getCartoonBySearch(String search) {
        if (StringUtils.isBlank(search)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "搜索关键字不能为空");
        }
        return getLatestPage(picCartoonMapper.getCartoonBySearch(search));
    }

    @Override
    public List<PicCartoon> getRandomCartoons() {
        List<Integer> cartoonIds = picCartoonMapper.getAllCartoonIds();
        Collections.shuffle(cartoonIds);
        //有前五个就取前五个,没有就全部
        if (cartoonIds.size() >= 5) {
            cartoonIds = cartoonIds.subList(0, 5);
        }
        if (cartoonIds.size()==0){
            return new LinkedList<>();
        }
        return getLatestPage(picCartoonMapper.getCartoonsByIds(cartoonIds));
    }

    @Override
    public List<PicCartoon> getRandomAdventureCartoons(String name) {
        if (StringUtils.isBlank(name)) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "题材名字不能为空");
        }
        PicCategory category = picCategoryMapper.getCategoryByName(name);
        Integer categoryId;
        List<Integer> cartoonIds;
        if (!Objects.isNull(category)){
            categoryId = category.getId();
            cartoonIds=picCartoonMapper.getCartoonIdsByCategory(categoryId);
        }else {
            //漫画要是呗删了就随便给
            cartoonIds = picCartoonMapper.getAllCartoonIds();
        }
        Collections.shuffle(cartoonIds);
        //有前五个就取前五个,没有就全部
        if (cartoonIds.size() >= 5) {
            cartoonIds = cartoonIds.subList(0, 5);
        }
        if (cartoonIds.size()==0){
            //给一个长度为0的集和,避免下面的空报错
            return new LinkedList<>();
        }
        return getLatestPage(picCartoonMapper.getCartoonsByIds(cartoonIds));
    }

    @Override
    public PicCartoon addCartoon(PicCartoon picCartoon) {
        String name = picCartoon.getName();
        Integer categoryId = picCartoon.getCategoryId();
        Integer regionId = picCartoon.getRegionId();
        String author = picCartoon.getAuthor();
        String introduction = picCartoon.getIntroduction();
        String cover = picCartoon.getCover();
        if (StringUtils.isBlank(name)){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画名字不能为空");
        }
        if (name.length()<1){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画名字长度必须大于等于1");
        }
        if (Objects.isNull(picCategoryMapper.getCategoryById(categoryId))){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画类型id不存在");
        }
        if (Objects.isNull(picRegionMapper.getRegionById(regionId))){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "国家类型id不存在");
        }
        if (StringUtils.isBlank(author)){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "作者名字不能为空");
        }
        if (author.length()<2){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "作者名字要大于或等于两个字符");
        }
        if (StringUtils.isBlank(introduction)){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画内容不能为空");
        }
        if (StringUtils.isBlank(cover)){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画封面路径不能为空");
        }
        picCartoonMapper.addCartoon(picCartoon);
        if (picCartoon.getId()<=0){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画插入失败");
        }
        return picCartoon;
    }

    @Override
    public PicCartoon getCartoonByName(String name) {
        if (StringUtils.isBlank(name)){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画名字不能为空");
        }
        PicCartoon cartoonByName = picCartoonMapper.getCartoonByName(name);
        if (Objects.isNull(cartoonByName)){
            throw new BusinessException(HttpStatus.NOT_FOUND, "不存在该漫画名字");
        }
        return cartoonByName;
    }

    /**
     * 该实现类共同用到的方法,专门给漫画类赋予最新更新的集数
     */
    public List<PicCartoon> getLatestPage(List<PicCartoon> cartoons) {
        for (PicCartoon cartoon : cartoons) {
            Integer page = picPageMapper.getPageCountByCartoonId(cartoon.getId());
            cartoon.setLatestPage(page);
        }
        return cartoons;
    }
    @Override
    public List<CartoonDto> getIndexRandomCartoons() {
        //1.获取所有漫画编号
        List<Integer> cartoonIds = picCartoonMapper.getAllCartoonIds();
        //2.打乱编号
        Collections.shuffle(cartoonIds);
        //3.取指定数量的编号
        cartoonIds = cartoonIds.subList(RANDOM_CARTOONS_START_OFFSET, RANDOM_CARTOONS_SHOW_COUNT);
        //4.根据漫画编号获取漫画信息
        List<PicCartoon> picCartoons = getLatestPage(picCartoonMapper.getCartoonsByIds(cartoonIds));
        List<CartoonDto> cartoonDtos = new ArrayList<>();
        picCartoons.stream().forEach(picCartoon -> {
            CartoonDto cartoonDto = new CartoonDto();
            cartoonDto.setId(picCartoon.getId());
            cartoonDto.setImgPath(picCartoon.getCover());
            cartoonDto.setUname(picCartoon.getAuthor());
            cartoonDto.setTitle(picCartoon.getName());
            cartoonDto.setCategoryName(CARTOON_CATEGORY_NAME);
            cartoonDtos.add(cartoonDto);
        });
        return cartoonDtos;
    }

    @Override
    public List<PicCartoon> getHotestCartoons() {
        //从Redis中去查找点击量在前10的这些商品的id信息
        //并根据这些id去查询商品的数据
        Set<String> redisHotestPids = redisOperations.zrevrange(
                REDIS_CARTOON_COLLECTION_COUNT_KEY,
                HOTEST_CARTOON_RANK_START_OFFSET,
                HOTEST_CARTOONS_SHOW_COUNT);
        List<Integer> cids = redisHotestPids.stream()
                .map(redisHotestPid -> Integer.parseInt(redisHotestPid))
                .collect(Collectors.toList());
        List<PicCartoon> cartoons = picCartoonMapper.getCartoonsByIds(cids);
        if (CollectionUtils.isEmpty(cartoons)) {
            throw new BusinessException(HttpStatus.NOT_FOUND, "不存在漫画信息");
        }
        return cartoons;
    }

}
